﻿class Mqtt {
    constructor() {
        this.hour = 0;
        this.minutes = 0;
        this.seconds = 0
        this.cr = "";
        this.interval = "00:00:00";
        this.timer = '';
    }
    startTimer(className) {
        this.seconds = this.seconds + 1;
        if (this.seconds >= 60) {
            this.seconds = 0;
            this.minutes = this.minutes + 1;
        }
        if (this.minutes >= 60) {
            this.minutes = 0;
            this.hour = this.hour + 1;
        }
        this.interval = (this.hour < 10 ? "0" + this.hour : this.hour) + ":" + (this.minutes < 10 ? "0" + this.minutes : this.minutes) + ":" + (this.seconds < 10 ? "0" + this.seconds : this.seconds);
        this.cr = this.seconds;
        $(`.${className}`)[0].innerHTML = this.interval
    } // 定时器，生成 00:00:00
    createTimer(className) {
        this.timer = setInterval(() => {
            this.startTimer(className)
        }, 1000);
    }//创建定时器
    destroyTimer() {
        clearInterval(this.timer)
        this.hour = 0;
        this.minutes = 0;
        this.seconds = 0
        this.cr = "";
        this.interval = "00:00:00";
    }// 销毁定时器
    pauseMusic() {
        $('#music')[0].pause()
        $('#music')[0].load()
    } //音乐停止播放 √
    customerSatus(flag, id) {
        switch (flag) {
            case 'leave':
                $('#' + id).find('img').attr('src', '/Content/trtc/img/leave.png')
                if ($('#' + id).find('.imgText').length > 0) {
                    $('#' + id).find('.imgText')[0].innerHTML = '离线'
                }
                $('#' + id).find('.operateBtn').css({ color: '#c0c4cc' })
                $('#' + id).find('.operateBtn').attr('disabled', 'disabled')
                break;
            case 'live':
                $('#' + id).find('img').attr('src', '/Content/trtc/img/live.png')
                if ($('#' + id).find('.imgText').length > 0) {
                    $('#' + id).find('.imgText')[0].innerHTML = '在线'

                }
                if ($('.calling').length > 0) {
                    if ($('.calling')[0].style.display === 'block') {
                        $('#' + id).find('.operateBtn').css({ color: '#2ecc71' })
                        $('#' + id).find('.operateBtn').attr('disabled', false)
                    }
                }
                break;
            case 'calling':
                $('#' + id).find('img').attr('src', '/Content/trtc/img/calling.png')
                if ($('#' + id).find('.imgText').length > 0) {
                    $('#' + id).find('.imgText')[0].innerHTML = '通话中'
                }
                $('#' + id).find('.operateBtn').css({ color: '#c0c4cc' })
                $('#' + id).find('.operateBtn').attr('disabled', 'disabled')
                break;
            case 'leaveMoment':
                $('#' + id).find('img').attr('src', '/Content/trtc/img/leaveMoment.jpg')
                if ($('#' + id).find('.imgText').length > 0) {
                    $('#' + id).find('.imgText')[0].innerHTML = '离开'
                }
                $('#' + id).find('.operateBtn').css({ color: '#c0c4cc' })
                $('#' + id).find('.operateBtn').attr('disabled', 'disabled')
                break;
        }
    } //客服状态
}
var hostname = 'tyzfbj.com',//'brianzhou.com.cn',//'kh.tyzfchina.com.cn'
    port = 8084//8084,
    clientId = guid(),
    mqtttimeout = 60, //IOT_MQTT_Yield会block住timeout的时间去尝试接收数据，直到timeout才会退出。
    keepAlive = 1,
    cleanSession = false,
    ssl = true, //true
    userName = 'admin',
    password = '123456_nikoyose_85189633',
    subscribeTopic = '',//订阅消息request_房间号：有人要加入房间0  离开1
    CancelTopic = '',//订阅消息cacel_手机号：客户端取消通话
    loginTopic = 'callcenter_request',// 订阅消息,发送消息:登录/退出/无应答
    isAgreeTopic = "client_request_isagree",//订阅消息,发送消息: 同意/拒绝加入房间
    isConnetion = false,
    joinpeer = "",
    notification = '',
    hour = 0, minutes = 0, seconds = 0, cr = "", interval = "00:00:00", timer ='',// 定时器
    noreply = ''
var mqttHome = new Mqtt() // 总台使用,修改客服人员状态
// var mqttIndex = '' //客服通讯页面使用 生成计时器
function guid() {
    function S4() {
        return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
    }
    return (S4() + S4() + "-" + S4() + "-" + S4() + "-" + S4() + "-" + S4() + S4() + S4());
}
function startMqtest() {
    clientId = guid();
    client = new Paho.MQTT.Client(hostname, port, clientId);
    //建立客户端实例
    var options = {
        invocationContext: {
            host: hostname,
            port: port,
            path: client.path,
            clientId: clientId
        },
        timeout: mqtttimeout,
        keepAliveInterval: keepAlive,
        cleanSession: cleanSession,
        useSSL: ssl,
        userName: userName,
        password: password,
        onSuccess: onConnect,
        onFailure: function (e) {
            console.log(e);
            s = "{time:" + new Date().Format("yyyy-MM-dd hh:mm:ss") + ", onFailure()}";
            console.log(s);
        }
    };
    client.connect(options);
    client.onConnectionLost = onConnectionLost;//注册连接断开处理事件
    client.onMessageArrived = onMessageArrived;
}
function onConnect() {
    console.log("onConnected=====================");
    switch (sessionStorage.getItem('role')) {
        case 'Caller':
            if (app.status === 'leaveMoment') {
                sendLogin(4) // 创建房间
            } else {
                sendLogin(0) // 创建房间
            }
            subscribeTopic = 'request_' + $('#roomId')[0].value;
            client.subscribe(subscribeTopic); //接收消息，有人要加入
            break;
        case 'ReceptionDesk':
            client.subscribe(loginTopic);
            client.subscribe(isAgreeTopic);
            break;
    }
    isConnetion = true;
    updateWsStatus(0) //此时之后 isconnection为false，又恰好到时间了执行了重连，变为

}//连接服务器并注册连接成功处理事件
function onConnectionLost(responseObject) {
    console.log("连接已断开");
    console.log("连接错误:" + responseObject.errorMessage);
    isConnetion = false;
    updateWsStatus(2)
}//注册消息接收处理事件
function onMessageArrived(message) {
    switch (sessionStorage.getItem('role')) {
        case 'Caller':
            if ($('#roomId')[0] && $('#roomId')[0].value) {// 房间存在
                subscribeTopic = 'request_' + $('#roomId')[0].value;
                // 客户端请求加入房间
                if (message.destinationName == subscribeTopic && JSON.parse(message.payloadString).Type === 0) {
                    notification = notifyMe() //桌面提示
                    $('#music')[0].play()// 来电铃声
                    let obj = jQuery.parseJSON(message.payloadString);
                    CancelTopic = 'cancel_' + obj.TelNum
                    client.subscribe(CancelTopic)
                    console.log('CancelTopic===========', CancelTopic)
                    joinpeer = obj.TelNum
                    
                    $('.myAlert').find('.el-button').trigger('click'); //客户退出弹窗隐藏
                    console.log('收到消息：客户请求加入房价', obj)
                    $('.callmark').removeClass('notshow') //显示来电弹窗
                    app.phoneNum = obj.TelNum
                    app.userId = obj.userId
                    app.accountName = obj.accountName
                    document.getElementsByClassName('myconfirmtext')[2].innerHTML = '请求' + (obj.Modeltype === 2 ? '视频' : '音频') + '通话'
                    $("#agree").off('click')
                    $("#reject").off('click')
                    $("#agree").click(function () {
                        if (Notification.permission === "granted" && notification) {
                            notification.close();//关闭桌面通知
                        }
                        app.isCalling = true
                        pauseMusic()
                        obj.isAgree = 'true'
                        obj.servicecallnum = $('#userId')[0].value //我的id
                        obj.call_sn = new Date().getTime() + '' // 13位
                        app.questionForm.callsn = obj.call_sn
                        sendMessageIsAgree(obj)
                        $('.callmark').addClass('notshow')
                        $('#header-time').removeClass('notshow')
                        document.getElementById('header-userID').innerHTML = joinpeer  // 来自XXX的电话
                        if (obj.Modeltype === 2) { //视频
                            if (!isCamOn) { //打开视频
                                $('#video-btn').trigger('click')
                            }
                            if (!isMicOn) { //打开麦克风
                                $('#mic-btn').trigger('click')
                            }
                        } else { // 音频
                            if (!isMicOn) { //打开麦克风
                                $('#mic-btn').trigger('click')
                            }
                            if (isCamOn) { //关掉视频
                                $('#video-btn').trigger('click')
                            }
                        }
                        app.calltime(obj.Modeltype)
                        console.log('noreply',noreply)
                        clearTimeout(noreply)
                        Evt.sendEvent('isCalling', true); // 发送事件：正在通话中（隐藏刷新和全屏按钮）
                        
                    }); // 同意
                    $("#reject").click(function () {
                        if (Notification.permission === "granted" && notification) {
                            notification.close();//关闭桌面通知
                        }
                        //app.callmark = false
                        pauseMusic()
                        obj.isAgree = 'false'
                        obj.servicecallnum = $('#userId')[0].value //我的id
                        sendMessageIsAgree(obj)
                        $('.callmark').addClass('notshow')
                        app.resetData() //状态复位
                        clearTimeout(noreply)
                    }); // 拒绝
                    if (!$('.callmark').hasClass('notshow')) { //弹窗展示120秒之后，按无应答处理
                        noreply = setTimeout(() => {
                            if (!$('.callmark').hasClass('notshow')) {
                                pauseMusic()
                                sendLogin(3)
                                $('.callmark').addClass('notshow')
                                Evt.sendEvent('missCallNotify', true);//针对已打开的页面：发送事件;

                                app.missCallNotifyBox = true //未接来电右下角表格展示
                                app.missCallNotify = true //未接来电右下角表格展开状态
                                app.resetData() //状态复位
                                setTimeout(function () {
                                    app.getMissCallData()
                                    app.light("#hometable_calllog .el-table__body-wrapper table tbody tr:nth-child(1)");
                                   // $('#icon-refresh').trigger('click') // 刷新客服通讯表格
                                }, 1000); //第一次闪烁
                                clearTimeout(noreply)
                            }
                        }, 1000 * 60) //收到来电之后的120秒 之后执行此方法
                    } //无应答
                }
                // 客户端离开房间
                if (message.destinationName == subscribeTopic && JSON.parse(message.payloadString).Type === 1) {
                    app.removePeer()
                }
                //客户端取消通话
                if (message.destinationName == CancelTopic) {
                    console.log('noreply', noreply)
                    clearTimeout(noreply)
                    pauseMusic()
                    $('.callmark').addClass('notshow')
                    app.cancelCall() // 客户取消通话请求弹窗
                    sendLogin(6)//告诉调度中心取消童话
                    CancelTopic = '' // 置空取消来电的topic
                    notification.close();//关闭桌面通知
                    Evt.sendEvent('missCallNotify', true);//针对已打开的页面：发送事件;  主页闪烁
                    app.missCallNotifyBox = true //未接来电右下角表格展示
                    app.missCallNotify = true //未接来电右下角表格展开状态
                    setTimeout(function () {
                        app.getMissCallData() //刷新右下角未接来电表格
                        app.light("#hometable_calllog .el-table__body-wrapper table tbody tr:nth-child(1)"); // 闪烁
                       // $('#icon-refresh').trigger('click') // 刷新客服通讯表格
                    }, 1000); //第一次闪烁
                }
            }// 收到有人要加入某个房间，通讯页面逻辑
            break;
        case 'ReceptionDesk':
            if (message.destinationName === isAgreeTopic) {
                let clientrRquestIsagree = jQuery.parseJSON(message.payloadString);
                if (clientrRquestIsagree.isAgree === 'true') {
                    mqttHome.customerSatus('calling', clientrRquestIsagree.servicecallnum.toString())
                }
            } // 同意加入房间，总台状态发生改变
            if (message.destinationName === loginTopic) {
                let callcenterRequest = jQuery.parseJSON(message.payloadString);
                console.log('收到消息，有人加入.离开房间', callcenterRequest.Type)
                switch (callcenterRequest.Type) { // 坐席人员加入type0  客户端离开1 坐席人员离开2 坐席人员 无应答3
                    case 0:
                        if ($('#' + callcenterRequest.RoomId).find('.imgText').length > 0) {
                            if (!($('#' + callcenterRequest.RoomId).find('.imgText')[0].innerHTML === '通话中')) {
                                mqttHome.customerSatus('live', callcenterRequest.servicecallnum.toString())
                            }
                        }
                        break;
                    case 1:
                        mqttHome.customerSatus('live', callcenterRequest.RoomId.toString())
                        break;
                    case 2:
                        mqttHome.customerSatus('leave', callcenterRequest.servicecallnum.toString())
                        break;
                    case 3:
                        mqttHome.customerSatus('live', callcenterRequest.servicecallnum.toString())
                        break;
                    case 4:
                        mqttHome.customerSatus('leaveMoment', callcenterRequest.servicecallnum.toString()) //暂时离开
                        break;
                    case 5:
                        mqttHome.customerSatus('live', callcenterRequest.servicecallnum.toString()) //暂时离开后又回来了
                        break;
                }
            } // 有人创建房间，有人离开房间,总台状态发生改变
            break
    }
}
function light(id) {
    $(id).css('background', 'red');  //默认值
    setTimeout(function () {
        $(id).css('background', '#fff');
    }, 1000); //第一次闪烁
    setTimeout(function () {
        $(id).css('background', 'red');
    }, 2000);

    setTimeout(function () {
        $(id).css('background', '#fff');
    }, 3000);
    setTimeout(function () {
        $(id).css('background', 'red');
    }, 4000);
    setTimeout(function () {
        $(id).css('background', '#fff');
    }, 5000);

    setTimeout(function () {
        $(id).css('background', 'red');
    }, 6000);
    setTimeout(function () {
        $(id).css('background', '#fff');
    }, 7000);

    setTimeout(function () {
        $(id).css('background', 'red');
    }, 8000);
    setTimeout(function () {
        $(id).css('background', '#fff');
    }, 9000);
}
function sendLogin(type) {
    var obj = {
        RoomId: Number($('#roomId')[0].value),
        userId: app.userId,
        TelNum: app.phoneNum,//type === 0 ? $('#userId')[0].value : (type === 4 ? $('#userId')[0].value : (type === 5 ? $('#userId')[0].value : joinpeer)),// string  0 4 5客服人员id    2joinpeer 3 join
        accountName: app.accountName,
        servicecallnum: $('#userId')[0].value,
        Type: type, // 加入 0 离开2 无应答3  取消6  踢出客户端7
        time: new Date().Format("yyyy-MM-dd hh:mm:ss"),
        businessType: 1, // 呼叫人员1 视频问诊2
        deptId: parseInt(app.deptId)
    }
    console.log('客服人员sendLogin', obj);
    message = new Paho.MQTT.Message(JSON.stringify(obj));
    message.destinationName = "callcenter_request";
    client.send(message);
} //客服人员创建房间，离开房间，无应答状态发送消息 √
function sendCuntomerLeave(roomId, userid, callmode) {
    let obj = {
        RoomId: roomId,
        Type: 1,//0: join 1: Leave
        Time: new Date().Format("yyyy-MM-dd hh:mm:ss"),
        UserId: userid,
        Modeltype: callmode,//1:音频 2:视频
        isAgree: false,
        TelNum: app.phoneNum,
    }
    console.log('踢出用户发送消息', obj)
    message = new Paho.MQTT.Message(JSON.stringify(obj));
    message.destinationName = "callcenter_request";
    client.send(message);
} // 踢出客户发送消息
function sendMessageIsAgree(obj) {
    obj.businessType = 1; // 呼叫人员1 视频问诊2
    let mqttMessage = new Paho.MQTT.Message(JSON.stringify(obj));
    mqttMessage.destinationName = 'client_request_isagree';
    client.send(mqttMessage);
    console.log('同意/拒绝加入房间', obj);
} // 同意、拒绝别人加入房间发送消息 √
function sendRequestRoomId(param1, param2) {
    var obj = {
        RoomId: param1,
        Type: 0,//0: join 1: Leave 2:客服leave
        Time: new Date().Format("yyyy-MM-dd hh:mm:ss"),
        userId: param2,
        Modeltype: 1,//0:video  1:voice
        isAgree: false,
        servicecallnum: param1,
        SubType: 1 //0:随机分配  1:手动分配 
    }
    console.log('给客服人员发消息进行转接', obj);
    message = new Paho.MQTT.Message(JSON.stringify(obj));
    message.destinationName = "request_" + param1;
    client.send(message);
}//发送消息给客户端：进行转入
function pauseMusic() {
    $('#music')[0].pause()
    $('#music')[0].load()
} //音乐停止播放 √
function stop() {
    window.clearInterval(window.tester);
}
function updateWsStatus(flag) {//在线 0 掉线1 正在重连2
    if ($('#header-wsstatus').length > 0 && $('#wsNotice').length > 0) {
        if (flag === 0) {
            app.wsStatusValue = '在线'
            app.offline = false
            $("#header-wsstatus").css({ "background-color": "#67c23a" });
            $('#wsNotice')[0].innerHTML = '[' + new Date().Format("yyyy-MM-dd hh:mm:ss") + '] websocket已连接'
        } else if (flag === 1) {
            app.wsCount++
            app.wsStatusValue = '掉线'
            app.offline = true
            $("#header-wsstatus").css({ "background-color": "red" });
            $('#wsNotice')[0].innerHTML = '[' + new Date().Format("yyyy-MM-dd hh:mm:ss") + '] websocket已断开'
        } else if (flag === 2) {
            app.wsCount++
            app.wsStatusValue = '掉线'
            app.offline = true
            $("#header-wsstatus").css({ "background-color": "red" });
            $('#wsNotice')[0].innerHTML = '[' + new Date().Format("yyyy-MM-dd hh:mm:ss") + '] websocket正在重连...'
        }
    }
}
function notifyMe() {
    var options = {
        body: 'Hi~有客户来电啦!',
        icon: '/Content/img/tian.jpg',
        requireInteraction: true
    }
    var theTitle = localStorage.getItem("DeptName") + '呼叫中心'
    // 先检查浏览器是否支持
    if (!("Notification" in window)) {
        alert("This browser does not support desktop notification");
    }
    // 检查用户是否同意接受通知
    else if (Notification.permission === "granted") {
        var notification1 = new Notification(theTitle, options);
        return notification1 // 返回参数 用于关闭桌面通知
        //notification.onshow = function () {
        //    notification.close();//关闭一个以前显示的通知。
        //    //setTimeout(notification.close.bind(notification), 4000);; //延时关闭
        //};
    }
    // 否则我们需要向用户获取权限
    else if (Notification.permission !== "denied") {
        Notification.requestPermission().then(function (permission) {
            if (permission === "granted") {
                var notification1 = new Notification(theTitle, options);
                return notification1

            }
        });
    }
}
setInterval(function () {
    if (!isConnetion) {
        console.log("正在重连...");
        updateWsStatus(2)
        startMqtest();
    }
    if (client == null) {
        console.log("正在重连...");
        updateWsStatus(2)
        startMqtest();
    }
}, 1000 * 5);
Date.prototype.Format = function (fmt) {
    var o = {
        "M+": this.getMonth() + 1, //月份
        "d+": this.getDate(), //日
        "h+": this.getHours(), //小时
        "m+": this.getMinutes(), //分
        "s+": this.getSeconds(), //秒
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度
        "S": this.getMilliseconds() //毫秒
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[
            k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
}
